<?php
class User extends AppModel
{
    var $name = 'User';
    var $hasOne = array(
    	'Portfolio' => array(
    		'className' => 'Portfolio',
    		'dependent' => true)
    );
    
    var $validate = array(
      'username' => array(
        'alphaNumeric' => array('rule' => 'alphaNumeric', 'required' => true),
        'maxLength' => array('rule' => array('maxLength', '45')),
        'isUnique' => array('rule' => 'isUnique')
      ),
      'email' => array(
        'isEmail' => array('rule' => array('email', false), 'required' => true ),
      	'maxLength' => array('rule' => array('maxLength', '255'))
      ),
      'confirmEmail' => array( 
      	'emailConfirmed' => array('rule' => array('confirmEmail'), 'required' => true, 'on' => 'create' )
      ),
      'confirmPassword' => array(
        'isPasswordComplex' => array('rule' => 'isPasswordComplex', 'required' => true, 'on' => 'create' )
      ),
      'password' => array(
      	'confirmPassword' => array('rule' => 'confirmPassword', 'required' => true, 'on' => 'create' )
      )
    );
    
    function register($data)
	{
		$user = false;
		
		//If the model validates then save a new user
		if ($this->create($data, true)) //Set filterKey to true. Stops faked ids updating existing user.
		{
			if($this->validates())
			{
				$user = $this->save(NULL, false, array('username', 'password', 'email')); //The whitelist does not cover the id field.

				//Generate a portfolio for the new user
				if($user)
				{
					$this->Portfolio->createPortfolioForUser($this->id);
					$user = $this->findById($this->id);
				}
			}
		}
		
		return $user;
	}
    
    function isPasswordComplex($user)
    {    
		$valid = false;
      
		if(preg_match('/(?=^.{5,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/', $user['confirmPassword']) )
		{
			$valid = true;
		}

		return $valid;
	}
    
    function confirmPassword($data)
	{
		$valid = false;

		if(isset($this->data['User']['confirmPassword']))
		{
			if ($data['password'] == Security::hash(Configure::read('Security.salt') . $this->data['User']['confirmPassword']))
	    	{
				$valid = true;
			}
		}

		return $valid;
    }
	
    function confirmEmail()
	{
		$valid = false;

		if(isset($this->data['User']['confirmEmail']) && isset($this->data['User']['email']))
		{
			if ($this->data['User']['email'] == $this->data['User']['confirmEmail'])
	    	{
				$valid = true;
			}
		}

		return $valid;
    }
      
    function isUsernameUnique($username)
    {
		$result = false;
   		$user = $this->findByUsername($username);

		if(empty($user) == true)
		{
			$result = true;
		}
	
		return $result;
    }
}
?>